import React, {
  memo,
  useCallback,
  useState,
  createElement,
  useEffect
} from 'react'
import { ArticleDiscussWrapper } from './style'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { Input, Button, Comment, Tooltip, message } from 'antd'
import moment from '@/utils/expandMoment'
import {
  LikeOutlined,
  LikeFilled,
  CloseSquareOutlined,
  CheckSquareOutlined
} from '@ant-design/icons'
import {
  deleteDiscussItem,
  getDiscussSupport,
  postReplyDiscuss
} from '@/network/blog/discuss.request'
import {
  changeDiscussAction,
  getArticleDiscussAction
} from '@/store/blog/actionCreators'
import { postDiscussItem } from '@/network/blog/discuss.request'
import { dateFormat } from '@/utils/common'

const { TextArea } = Input

function B_ArticleDiscuss(props) {
  const { articleId } = props
  const [articleDiscussCopy, setArticleDiscussCopy] = useState([])
  const [inputValue, setInputValue] = useState('')
  const [disabled, setDisabled] = useState(true)
  const localUser = JSON.parse(localStorage.getItem('user')) || {}
  const dispatch = useDispatch()

  const { articleDiscuss = [], userProfile = {} } = useSelector(
    (state) => ({
      articleDiscuss: state.blogReducer.getIn(['articleDiscuss']),
      userProfile: state.blogReducer.getIn(['userProfile'])
    }),
    shallowEqual
  )

  useEffect(() => {
    setArticleDiscussCopy(articleDiscuss)
  }, [articleDiscuss])

  const onChangeInput = useCallback((e) => {
    setInputValue(e.target.value)
    e.target.value.trim() ? setDisabled(false) : setDisabled(true)
  }, [])

  // 切换点赞
  const toggleLike = useCallback(
    async (index, indey, discussId, likeByUserId, userId) => {
      if (localUser && localUser.id) {
        let copyItem = [...articleDiscussCopy]
        const result = await getDiscussSupport(discussId)
        if (result.isSupport) {
          // 点赞
          if (indey === null) {
            // 第1层 0 null 1 [9] 8
            if (!likeByUserId) {
              // 还没人点赞
              copyItem[index].likeByUserId = []
            }
            // 添加点赞
            copyItem[index].likeByUserId.push(userId)
            copyItem[index].likes += 1
          } else {
            // 第2层  0 0 8 null 8
            if (!likeByUserId) {
              // 还没人点赞
              copyItem[index].childDiscuss[indey].likeByUserId = []
            }
            // 添加点赞
            copyItem[index].childDiscuss[indey].likeByUserId.push(userId)
            copyItem[index].childDiscuss[indey].likes += 1
          }
        } else {
          // 取消点赞
          if (indey === null) {
            // 第1层 0 null 1 [9] 8
            // 取消点赞
            copyItem[index].likeByUserId = copyItem[index].likeByUserId.filter(
              (item) => item !== userId
            )
            copyItem[index].likes -= 1
          } else {
            // 第2层  0 0 8 [9,8] 8
            // 取消点赞
            copyItem[index].childDiscuss[indey].likeByUserId = copyItem[
              index
            ].childDiscuss[indey].likeByUserId.filter((item) => item !== userId)
            copyItem[index].childDiscuss[indey].likes -= 1
          }
        }
        // 更新数据
        dispatch(changeDiscussAction(copyItem))
      } else {
        // 未登录
        message.info('未登录~')
      }
    },
    [articleDiscussCopy, dispatch, localUser]
  )

  // 添加一条评论
  const submitDiscuss = useCallback(() => {
    if (localUser && localUser.id) {
      postDiscussItem(articleId, inputValue)
        .then((res) => {
          if (res.insertId) {
            // 评论成功
            setInputValue('')
            setDisabled(true)
            dispatch(getArticleDiscussAction(articleId))
          }
        })
        .catch(console.log)
    } else {
      // 未登录
      message.info('未登录~')
    }
  }, [articleId, inputValue, dispatch, localUser])

  // 删除一条评论
  const deleteDiscuss = useCallback(
    (discussId) => {
      deleteDiscussItem(discussId)
        .then((res) => {
          if (res.affectedRows) {
            // 删除成功
            dispatch(getArticleDiscussAction(articleId))
          }
        })
        .catch(console.log)
    },
    [articleId, dispatch]
  )

  // 回复一条评论
  const [reply, setReply] = useState(false)
  const [replyDis, setReplyDis] = useState(0)
  const [replyText, setReplyText] = useState('')
  const replyDiscuss = useCallback((discussId) => {
    setReplyDis(discussId)
    setReply(true)
  }, [])

  // 提交回复评论
  const submitReply = useCallback(() => {
    if (localUser && localUser.id) {
      postReplyDiscuss(articleId, replyDis, replyText).then((res) => {
        if (res.insertId) {
          // 评论成功
          dispatch(getArticleDiscussAction(articleId))
          setReply(false)
          setReplyText('')
        }
      })
    } else {
      // 未登录
      message.info('未登录~')
    }
  }, [replyText, articleId, replyDis, dispatch, localUser])

  const getActions = useCallback(
    (
      index,
      indey,
      discussId,
      likeCount,
      likeByUserId = [],
      isReply,
      isDelete
    ) => {
      const isLike =
        (likeByUserId &&
          likeByUserId.length > 0 &&
          likeByUserId.includes(localUser.id)) ||
        false
      return [
        <Tooltip key="comment-basic-like" title="Like">
          <span
            onClick={(e) =>
              toggleLike(index, indey, discussId, likeByUserId, localUser.id)
            }
          >
            {createElement(isLike ? LikeFilled : LikeOutlined)}
            <span className="comment-action">{likeCount}</span>
          </span>
        </Tooltip>,
        isReply && (
          <span
            key="comment-basic-reply-to"
            onClick={(e) => replyDiscuss(discussId)}
          >
            回复
          </span>
        ),
        isDelete && (
          <span
            key="comment-basic-delete-to"
            onClick={(e) => deleteDiscuss(discussId)}
          >
            删除
          </span>
        )
      ]
    },
    [localUser.id, toggleLike, deleteDiscuss, replyDiscuss]
  )

  return (
    <ArticleDiscussWrapper className="animate__animated animate__zoomIn">
      <div className="input-box">
        <div className="left pr-3">
          <img
            src={
              (userProfile.user && userProfile.user.avatarUrl) ||
              'https://upload-images.jianshu.io/upload_images/20040970-e90f40f0617bb932.jpg'
            }
            alt={userProfile.user && userProfile.user.nickname}
            width="70px"
          />
          <p className="nickname">
            {userProfile.user && userProfile.user.nickname}
          </p>
        </div>
        <div className="right">
          <TextArea
            placeholder="说点啥呢"
            value={inputValue}
            allowClear
            onChange={onChangeInput}
            rows={4}
            cols={80}
            showCount={true}
            maxLength={200}
            className="discuss-input"
          />
          <p style={{ textAlign: 'right', paddingTop: '26px' }}>
            <Button
              onClick={submitDiscuss}
              type="primary emit-discuss"
              disabled={disabled}
            >
              发表评论
            </Button>
          </p>
        </div>
      </div>
      <div className="discuss-box">
        <ul>
          {articleDiscussCopy.length > 0 &&
            articleDiscussCopy.map((item, index) => {
              return (
                <li key={item.id} className="px-5">
                  <Comment
                    actions={getActions(
                      index,
                      null,
                      item.id,
                      item.likes,
                      item.likeByUserId,
                      true,
                      localUser.id === item.author.id
                    )}
                    author={
                      <a
                        href={`/blog/home/u/${item.author.id}`}
                        target="_blank"
                        className="text-decoration"
                        title={item.author.nickname}
                        rel="noopener noreferrer"
                      >
                        {item.author.nickname}
                      </a>
                    }
                    avatar={
                      <img
                        src={
                          item.author.avatarUrl ||
                          'https://upload-images.jianshu.io/upload_images/20040970-e90f40f0617bb932.jpg'
                        }
                        alt={item.author.nickname}
                        style={{ width: '50px', height: '50px' }}
                      />
                    }
                    content={<p>{item.content}</p>}
                    datetime={
                      <Tooltip title={moment(item.createTime).format('lll')}>
                        <span>{dateFormat(item.createTime)}</span>
                      </Tooltip>
                    }
                  >
                    {reply && item.id === replyDis && (
                      <div className="reply-1 animate__animated animate__zoomIn">
                        <Input
                          autoFocus
                          className="reply-1-input"
                          value={replyText}
                          placeholder="回复内容.."
                          maxLength={200}
                          onChange={(e) => setReplyText(e.target.value)}
                          size="small"
                        />
                        <CloseSquareOutlined
                          onClick={(e) => setReply(false)}
                          className="reply-icon"
                        />
                        <CheckSquareOutlined
                          onClick={submitReply}
                          className="reply-icon"
                        />
                      </div>
                    )}
                    {item.childDiscuss &&
                      item.childDiscuss.map((item, indey) => {
                        return (
                          <div key={item.id}>
                            <Comment
                              actions={getActions(
                                index,
                                indey,
                                item.id,
                                item.likes,
                                item.likeByUserId,
                                false,
                                localUser.id === item.author.id
                              )}
                              author={
                                <a
                                  href={`/blog/home/u/${item.author.id}`}
                                  target="_blank"
                                  className="text-decoration"
                                  rel="noopener noreferrer"
                                  title={item.author.nickname}
                                >
                                  {item.author.nickname}
                                </a>
                              }
                              avatar={
                                <img
                                  src={
                                    item.author.avatarUrl ||
                                    'https://upload-images.jianshu.io/upload_images/20040970-e90f40f0617bb932.jpg'
                                  }
                                  alt={item.author.nickname}
                                  style={{ width: '50px', height: '50px' }}
                                />
                              }
                              content={<p>{item.content}</p>}
                              datetime={
                                <Tooltip
                                  title={moment(item.createTime).format('lll')}
                                >
                                  <span>{dateFormat(item.createTime)}</span>
                                </Tooltip>
                              }
                            />
                          </div>
                        )
                      })}
                  </Comment>
                </li>
              )
            })}
        </ul>
      </div>
    </ArticleDiscussWrapper>
  )
}

export default memo(B_ArticleDiscuss)
